package com.loe.scan;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.king.zxing.CaptureHelper;
import com.king.zxing.Intents;
import com.king.zxing.OnCaptureCallback;
import com.king.zxing.ViewfinderView;
import com.king.zxing.util.CodeUtils;

public class ScanFragment extends Fragment
{
    private View rootView;

    private SurfaceView surfaceView;

    private ViewfinderView viewfinderView;

    private CaptureHelper mCaptureHelper;

    public static ScanFragment newInstance()
    {
        ScanFragment fragment = new ScanFragment();
        Bundle args = new Bundle();
        //        args.putString("param1", param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (getArguments() != null)
        {
            //            mParam1 = getArguments().getString("");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        rootView = inflater.inflate(R.layout.scan_fragment, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
    {
        surfaceView = rootView.findViewById(R.id.surfaceView);
        viewfinderView = rootView.findViewById(R.id.viewfinderView);

        PermissionUtil.requestTip(getActivity(), "", PermissionUtil.CAMERA, new PermissionUtil.OnPermissionCallback()
        {
            @Override
            public void onOk()
            {
                init();
            }

            @Override
            public void onError()
            {
                Toast.makeText(getContext(), "缺少相机权限", Toast.LENGTH_SHORT).show();
                finishOut();
            }
        });
    }

    private void init()
    {
        mCaptureHelper = new CaptureHelper(this, surfaceView, viewfinderView);
        mCaptureHelper.onCreate();
        mCaptureHelper.vibrate(false).fullScreenScan(true).supportVerticalCode(true).supportAutoZoom(false).continuousScan(true);
        mCaptureHelper.getBeepManager().setPlayBeep(true);
        mCaptureHelper.setOnCaptureCallback(new OnCaptureCallback()
        {
            @Override
            public boolean onResultCallback(String result)
            {
                if (isScanning)
                {
                    if (onResult != null)
                    {
                        onResult.onString(result == null ? "" : result);
                    }
                }
                return true;
            }
        });

        rootView.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                mCaptureHelper.onTouchEvent(event);
                return false;
            }
        });
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if (mCaptureHelper != null)
        {
            mCaptureHelper.onResume();
        }
    }

    @Override
    public void onPause()
    {
        super.onPause();
        if (mCaptureHelper != null)
        {
            mCaptureHelper.onPause();
        }
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (mCaptureHelper != null)
        {
            mCaptureHelper.onDestroy();
        }
    }

    public void finishOut()
    {
        getActivity().finish();
        if (LoeScan.onDestroyAnimate != null)
        {
            LoeScan.onDestroyAnimate.onOut(getActivity());
        }
    }

    public ViewfinderView getViewfinderView()
    {
        return viewfinderView;
    }

    private boolean isScanning = true;

    public boolean isScanning()
    {
        return isScanning;
    }

    public void setScanning(boolean scanning)
    {
        if (mCaptureHelper == null)
        {
            return;
        }
        isScanning = scanning;
        mCaptureHelper.getBeepManager().setPlayBeep(scanning);
        if (isScanning)
        {
            mCaptureHelper.restartPreviewAndDecode();
        }
    }

    private int getStatusHeight()
    {
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && resourceId > 0)
        {
            int heightSize = getResources().getDimensionPixelSize(resourceId);
            return heightSize;
        }
        else
        {
            return 0;
        }
    }

    /**
     * 关闭闪光灯（手电筒）
     */
    private void offFlash()
    {
        if (mCaptureHelper == null)
        {
            return;
        }
        Camera camera = mCaptureHelper.getCameraManager().getOpenCamera().getCamera();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
    }

    /**
     * 开启闪光灯（手电筒）
     */
    public void openFlash()
    {
        if (mCaptureHelper == null)
        {
            return;
        }
        Camera camera = mCaptureHelper.getCameraManager().getOpenCamera().getCamera();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
    }

    /**
     * 点击相册
     */
    public void clickAlbum()
    {
        PermissionUtil.requestTip(getActivity(), "", PermissionUtil.STORAGE, new PermissionUtil.OnPermissionCallback()
        {
            @Override
            public void onOk()
            {
                Intent pickIntent;
                if ("Xiaomi".equals(Build.MANUFACTURER))
                {
                    pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
                }
                else
                {
                    pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                ScanResultUtil.startResult(getActivity(), pickIntent, new ScanResultUtil.OnActivityResultListener()
                {
                    @Override
                    public void onActivityResult(int resultCode, Intent data)
                    {
                        if (resultCode == Activity.RESULT_OK && data != null)
                        {
                            parsePhoto(data);
                        }
                    }
                });
            }

            @Override
            public void onError()
            {
            }
        });
    }

    private void parsePhoto(Intent data)
    {
        final String path = ScanUriUtil.INSTANCE.getImagePath(getContext(), data);
        if (TextUtils.isEmpty(path))
        {
            return;
        }
        //异步解析
        new Thread()
        {
            @Override
            public void run()
            {
                final String result = CodeUtils.parseCode(path);
                rootView.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if (onResult != null)
                        {
                            onResult.onString(result == null ? "" : result);
                        }
                    }
                });
            }
        }.start();
    }

    private LoeScan.OnStringCallback onResult;

    public void setOnResult(LoeScan.OnStringCallback onResult)
    {
        this.onResult = onResult;
    }

    /**
     * 点击灯光
     */
    public void clickLight(View v)
    {
        if (v.isSelected())
        {
            offFlash();
            v.setSelected(false);
        }
        else
        {
            openFlash();
            v.setSelected(true);
        }
    }
}